layui.define(['jquery'], function (exports) {
	var $ = layui.jquery,
		closeAnimClass = 'layer-anim-close',
		layerObj = {
			indexId: {},
			idIndex: {},
			id_layui: {}
		}

	var obj = {
		/**
		 * * layui.admin.popupRight 的改造优化
		 * @param {Object} forceOptions 改造功能的自定义启用
		 * @param {Object} layerOptions 一些用于 layer.open 的参数
		 */
		open: function (forceOptions, layerOptions, win) {
			var _this = this,
				_popupRightLayer = {
					type: 1,
					id: 'LAY_adminPopupR',
					anim: -1,
					title: ' ',
					closeBtn: false,
					offset: 'r',
					shade: 0.1,
					shadeClose: true,
					skin: 'layui-anim layui-anim-rl my-anim-rl my-forcePopupRight',
					area: '300px'
				},
				_forceOptions = {
					autoHeight: false, //自动高度: 上下居中位置弹出（原理通过计算 top）; 固定高度: 默认 admin 侧边栏类型（固定 top、 bottom）
					adjWidth: false, //TODO:可调节宽度
					adjHeight: false, //TODO:可调节高度
					noHideDom: true, //隐藏时不删除 dom
					addSkin: '', //class
					css: '', //layui-layer-page css 字符串
					contentCss: '', //layui-layer-content css 字符串
					reload: false, //重新创建侧边栏
					$iframeLoad: null, //iframe 加载完成事件
					toggle: null //被动显示隐藏回调 function (e) {}
				},
				_layerOptions = {
					shadeClose: false
				},
				id = layerOptions['id']

			!!win || (win = window)
			var _layui = win.layui,
				_layer = _layui.layer

			$.extend(_forceOptions, forceOptions)
			$.extend(_layerOptions, layerOptions, {
				success: function (layero, index) {
					!layerOptions['success'] || layerOptions['success'](index, layero)

					var $iframe = layero.find('iframe')
					if ($iframe.length > 0) {
						//包含 iframe 则监听其加载完成 触发窗口变化事件, 保证侧边栏定位正常
						$iframe.on('load', function () {
							!_forceOptions.$iframeLoad || _forceOptions.$iframeLoad($iframe)
							var myEvent = new Event('resize')
							setTimeout(function () {
								win.dispatchEvent(myEvent)
							}, 500)
						})
					}

					!_forceOptions['toggle'] || _forceOptions['toggle']({ even: 'show', id: id, layero: layero, index: index }) //显示隐藏回调

					if (_forceOptions['noHideDom']) {
						//隐藏时不删除 dom
						layerObj[id] = {}
						layerObj[id]['$popupRight'] = layero
						layerObj[id]['$shade'] = _layui.$('#layui-layer-shade' + layero.attr('times'))

						layerObj['indexId'][index] = id
						layerObj['idIndex'][id] = index
						layerObj['id_layui'][id] = _layui

						layerObj[id]['$shade'].on('click', function () {
							//自定义遮罩点击事件, 隐藏
							_this.hide(id)

							!_forceOptions['toggle'] || _forceOptions['toggle']({ even: 'hide', id: id, layero: layero, index: index }) //显示隐藏回调
						})
					} else {
						layerObj[id]['$shade'].on('click', function () {
							//自定义遮罩点击事件, 移除
							_layer.close(index)
						})
					}
				}
			})

			if (_layui.$('#' + id).length > 0 && !layerObj['idIndex'][id]) {
				//已存在创建元素，则先卸载
				var index = _layui
					.$('#' + id)
					.parent()
					.attr('times')
				_layui.$('[times="' + index + '"]').remove()
				// _layer.close(_layui.$('#' + id).parent().attr('times'))
			}

			if (!_layui.admin || !_layer) return

			if (_forceOptions['reload']) {
				//移除侧边栏 dom
				_this.delete(id, true)
			}

			if (_this.show(id)) {
				//已渲染过 popupRight, 可直接显示
				!_forceOptions['toggle'] || _forceOptions['toggle']({ even: 'show', id: id, layero: layerObj[id]['$popupRight'], index: layerObj['idIndex'][id] }) //显示隐藏回调
				return
			}
			if (!_layui['forcePopupRighted']) {
				//如果次 window 未渲染过 forcePopupRight
				/** 添加默认样式 */
				_layui
					.$('head')
					.append(
						[
							'<style>',
							'.my-forcePopupRight{max-width: 90vw;max-height: 80vh;box-shadow:1px 1px 10px rgba(0,0,0,.1);border-radius:0;overflow:visible;transition: top 0.1s ease 0s;}',
							'.my-forcePopupRight .layui-layer-content{max-height: 80vh;}',
							'.my-forcePopupRight-initHeight{top:50px!important;bottom:0}',
							'.my-forcePopupRight-autoHeight{}',
							'.my-forcePopupRight .default_hieght{height: 300px}',	//用于 content 强制高度
							'.my-forcePopupRight .my-nullData{display:none;padding:30px;height:300px;align-items:center;justify-content:center;font-size:17px;font-weight:400;letter-spacing:.066em;color:#afafaf;}.my-forcePopupRight .my-nullData_show{display:flex;}', //无数据样式
							'@-webkit-keyframes my-lr{from{-webkit-transform:translate3d(0 0,0);opacity:1}to{-webkit-transform:translate3d(100vw,0,0);opacity:1}}@keyframes my-lr{from{transform:translate3d(0,0,0)}to{transform:translate3d(100vw,0,0)}}.my-anim-rl.layer-anim-close{-webkit-animation-name:my-lr;animation-name:my-lr}',
							'</style>'
						].join('')
					)
				_layui['forcePopupRighted'] = true
			}

			var cusCssId = 'my-forcePopupRighted-cusCss-' + id
			$cusCss = _layui.$('#' + cusCssId)
			if ($cusCss.length > 0) $cusCss.remove()
			_layui
				.$('head')
				.append(
					[
						'<style id="' + cusCssId + '">',
						'.' + cusCssId + '{' + _forceOptions['css'] + '}',
						'.' + cusCssId + ' .layui-layer-content{' + _forceOptions['contentCss'] + '}',
						'.' + cusCssId + ' .layui-layer-title{' + (_layerOptions['title'] ? '' : 'cursor:move;border:0;background-color:transparent;position:absolute;width:100%;top:-42px') + '}',
						'</style>'
					].join('')
				)

			_popupRightLayer['skin'] += ' ' + _forceOptions['addSkin'] //新增 class
			_popupRightLayer['skin'] += ' ' + cusCssId //新增自定义 css

			if (!_forceOptions['autoHeight']) {
				//默认非自动高度
				_popupRightLayer['skin'] += ' my-forcePopupRight-initHeight'
			}

			_layer.open($.extend(_popupRightLayer, _layerOptions))
		},
		/**
		 * * 显示已隐藏的 popupRight
		 * @param {String} id popupRight 的 id
		 */
		show: function (id) {
			if (!layerObj[id]) {
				// console.log('无法显示：未找到', id, '元素')
				return false
			}

			layerObj[id]['$shade'].show()
			layerObj[id]['$popupRight'].removeClass(closeAnimClass)
			return layerObj[id]['$popupRight'] //将被作为 if 判断
		},
		/**
		 * * 隐藏 popupRight
		 * @param {String} id popupRight 的 id
		 */
		hide: function (id) {
			if (!layerObj[id]) return false

			layerObj[id]['$shade'].hide()
			layerObj[id]['$popupRight'].addClass(closeAnimClass)
			return layerObj[id]['$popupRight']
		},
		/**
		 * * 销毁 popupRight dom元素
		 * @param {String} id popupRight 的 id
		 * @param {Boolean} rDom 是否直接移除dom, 非调用 _layer.close 防止造成异步
		 */
		delete: function (id, rDom) {
			if (!layerObj[id]) return

			var index = layerObj['idIndex'][id],
				_layui = layerObj['id_layui'][id]
			delete layerObj[id]
			delete layerObj['indexId'][index]
			delete layerObj['idIndex'][id]
			delete layerObj['id_layui'][id]

			if (rDom) {
				_layui.$('[times="' + index + '"]').remove()
			} else {
				_layui.layer.close(index)
			}

			var cusCssId = 'my-forcePopupRighted-cusCss-' + id
			_layui.$('#' + cusCssId).remove()
		}
	}

	window.addEventListener('beforeunload', function (event) {
		//卸载当前页前，先将在次 window 产生的 侧边栏相关dom 卸载
        $.each(layerObj['idIndex'], function (id, _layer) {
			obj.delete(id)
		})
	});


	//输出接口
	exports('forcePopupRight', obj)
})
